var viewModel = {
    //data
    folders: ['Reçus', 'Archive','Envoyés'],
    selectedFolder: ko.observable("Reçus"),
    selectedPMId:   ko.observable(),
    currentPagePM:  ko.observableArray([]),
    //Behaviours
    setIsRead: function(pm_id){
        if(this.pmIsReadRequest) this.pmIsReadRequest.abort();
        this.pmIsReadRequest = $.get('/pm/show', {id: pm_id});
    },
    selectFolder: function(folder){
        this.selectedFolder(folder);
        this.selectedPMId(null);

    }
    
};
viewModel.selectedPM = ko.dependentObservable(function(){
    var pmIdToFind = this.selectedPMId();
    var pm = ko.utils.arrayFirst(viewModel.currentPagePM(), function(item){ return item.id == pmIdToFind});
    if(pm != null)
        if(!pm.isRead)
            this.setIsRead(pmIdToFind);
   
    return pm;
}, viewModel);

window.pmViewModel = viewModel
ko.applyBindings(viewModel);

ko.dependentObservable(function(){
    if(this.pmLastRequest) this.pmLastRequest.abort();

    this.pmLastRequest = $.get('/pm/index', {folder: this.selectedFolder()}, this.currentPagePM);
}, viewModel);

ko.linkObservableToUrl(viewModel.selectedFolder, "folder", "Reçus");
ko.linkObservableToUrl(viewModel.selectedPMId, "pmId");
